/**
 * 2013 2013-5-8
 * @author cvxc,vkjxckb
 */
package com.surfilter.dp.view;

import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import com.surfilter.dp.constant.Constants;
import com.surfilter.dp.context.ContextHolder;
import com.surfilter.dp.dao.ModuleDao;
import com.surfilter.dp.model.ActionModel;
import com.surfilter.dp.model.ModuleModel;

/**
 * @author cvxc,vkjxckb
 *
 */
public class ModuleTree extends JTree {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9072730763374732440L;

	private ModuleDao moduleDao;
	
	private List<ModuleModel> allModules = null;
	
	private Map<String,ModuleModel> moduleMap = new HashMap<String,ModuleModel>();
	
	private ModuleModel selectedModule;
	
	private static DefaultMutableTreeNode root ; 
	
	private DefaultTreeModel treeModel;
	
	
	static {
		ModuleModel rootModel = new ModuleModel();
		rootModel.setModuleText("模块树");
		rootModel.setModuleName("root");
		root = new DefaultMutableTreeNode(rootModel);
	}
	
	
	public ModuleTree(){
		super(root);
		treeModel = new DefaultTreeModel(root);
		this.moduleDao = ContextHolder.getInstance().getModuleDao();
		initData();
		initView();
		initListener();
	}
	
	/**
	 * 
	 */
	private void initListener() {
		this.addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				TreePath path = e.getNewLeadSelectionPath();
				if(path != null){
					ModuleModel selected = (ModuleModel)((DefaultMutableTreeNode)path.getLastPathComponent()).getUserObject();
					ContextHolder.getInstance().getModuleTree().setSelectedModule(selected);
					if(!"root".equals(selected.getModuleName())){
						ContextHolder.getInstance().getModulePanel().setFormValue(selected);
						if(selected.getModuleType() == Constants.TYPE_FUN){  //功能模块
							if(selected.getId() == 0){
								selected = ContextHolder.getInstance().getModuleDao().getModuleByName(selected.getModuleName());
								ContextHolder.getInstance().getModuleTree().setSelectedModule(selected);
							}
							List<ActionModel> actions = ContextHolder.getInstance().getActionDao().getActionByModuleId(selected.getId());
							ContextHolder.getInstance().getActionPanel().setTableData(actions);
						}
					}
				}
			}
		});
	}

	public void initData() {
		this.allModules = moduleDao.getAllModules();
		moduleMap.clear();
		for (ModuleModel model : this.allModules) {
			String moduleName = model.getModuleName();
			moduleMap.put(moduleName, model);
		}
	}
	

	/**
	 * 
	 */
	public void initView() {
		createTreeNode(root);	
		this.setCellRenderer(new ModuleTreeCellRender());
		expandAll();
	}
	
	public void refresh(){
		root.removeAllChildren();
		this.initData();
		this.initView();
		this.updateUI();
	}
	
	
	/**
	 * 递归展开树
	 */
	public void expandAll(){
		expandChild(root);
	}
	
	private void expandChild(DefaultMutableTreeNode node){
		int childCount = treeModel.getChildCount(node);
		for (int i = 0; i < childCount; i++) {
			DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
			expandPath(new TreePath(treeModel.getPathToRoot(child)));
			if(!child.isLeaf()){
				expandChild(child);
			}
		}
	}
	
	public void closeAll(){
		this.collapsePath(new TreePath(root));
	}
	
	
	/**
	 * 递归构成树
	 * @param node
	 */
	private void createTreeNode(DefaultMutableTreeNode node){
		ModuleModel module = (ModuleModel)node.getUserObject();
	    String pname = module.getModuleName();
	    List<ModuleModel> childNodes = getChildNodes(pname);
	    for (ModuleModel child : childNodes) {
	    	DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child); 
			if(child.getModuleType() == Constants.TYPE_FOLDER){  //目录模块
				node.add(childNode);
				createTreeNode(childNode);
			} else if(child.getModuleType() == Constants.TYPE_FUN){ //功能模块
				node.add(childNode);
			}
		}
	}

	/**
	 * @param pname
	 * @return
	 */
	public List<ModuleModel> getChildNodes(String pname) {
		List<ModuleModel> retList = new ArrayList<ModuleModel>();
		for(ModuleModel module : this.allModules){
			if(pname.equals(module.getPname())){
				retList.add(module);
			}
		}
		return retList;
	}
	//修改当前选中节点
	public void updateCurrentNode(ModuleModel model){
		DefaultMutableTreeNode current =  (DefaultMutableTreeNode)this.getSelectionPath().getLastPathComponent();
		current.setUserObject(model);
		this.updateUI();
	}
	
	/**
	 * 删除当前节点
	 * @param module
	 */
	public void deleteCurrentNode() {
		DefaultMutableTreeNode current =  (DefaultMutableTreeNode)this.getSelectionPath().getLastPathComponent();
		DefaultMutableTreeNode parent = (DefaultMutableTreeNode)current.getParent();
		parent.remove(current);
		this.updateUI();
	}
	
	/**
	 * 插入新节点
	 * @param model
	 */
	public void addNewNode(ModuleModel model) {
		DefaultMutableTreeNode current =  (DefaultMutableTreeNode)this.getSelectionPath().getLastPathComponent();
		treeModel.insertNodeInto(new DefaultMutableTreeNode(model), current, current.getChildCount());
		this.updateUI();
	}
	

	/* (non-Javadoc)
	 * @see javax.swing.JTree#convertValueToText(java.lang.Object, boolean, boolean, boolean, int, boolean)
	 */
	@Override
	public String convertValueToText(Object value, boolean selected,
			boolean expanded, boolean leaf, int row, boolean hasFocus) {
		// TODO Auto-generated method stub
		if(value instanceof DefaultMutableTreeNode){
			if(((DefaultMutableTreeNode) value).getUserObject() instanceof ModuleModel)
			value = ((ModuleModel)((DefaultMutableTreeNode)value).getUserObject()).getModuleText();
		}
		return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
	}
	
	
	@SuppressWarnings("serial")
	class ModuleTreeCellRender extends DefaultTreeCellRenderer{

		/* (non-Javadoc)
		 * @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean)
		 */
		@Override
		public Component getTreeCellRendererComponent(JTree tree, Object value,
				boolean sel, boolean expanded, boolean leaf, int row,
				boolean hasFocus) {
			// TODO Auto-generated method stub
			super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
					row, hasFocus);
			int moduleType = ((ModuleModel)((DefaultMutableTreeNode)value).getUserObject()).getModuleType();
			if(moduleType == Constants.TYPE_FOLDER){    //设置目录模块图标
				this.setIcon(new ImageIcon(ModuleTree.class.getResource("/images/folder.gif")));
			}else if(moduleType == Constants.TYPE_FUN){  //设置功能模块图标
				this.setIcon(new ImageIcon(ModuleTree.class.getResource("/images/leaf.gif")));
			}else {   //设置根模块图标
			}
			return this;
		}
	}

	/**
	 * @return the selectedModule
	 */
	public ModuleModel getSelectedModule() {
		return selectedModule;
	}

	/**
	 * @param selectedModule the selectedModule to set
	 */
	public void setSelectedModule(ModuleModel selectedModule) {
		this.selectedModule = selectedModule;
	}
}
